package com.axapoint.opoc.service;

import generated.Organisation;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.joda.time.DateTime;

import com.axapoint.opoc.core.dao.AbstractFacade;

public abstract class AbstractMapper<FacadeType extends AbstractFacade> {

	// Keep track of objects traversed by this thread
	private static ThreadLocal<HashMap<String, String>> traversed = new ThreadLocal <HashMap<String, String>> () {
        @Override protected HashMap<String, String> initialValue() {
            return new HashMap<String, String>();
        }
	};

	protected final FacadeType facade;
	protected final String userId;
	protected final String systemId;
	
	protected AbstractMapper(FacadeType facade) {
		this.facade = facade;
		this.userId = facade.getUserId();
		this.systemId = facade.getSystemId();
	}
	
	public void passiver(String uuid, String kommentar) {
		
		facade.passivate(uuid, kommentar);
	}

	public void slet(String uuid, String kommentar) {
		facade.delete(uuid, kommentar);
	}

	public void glem(String uuid, DateTime vTime) {
		facade.forget(uuid, vTime);
	}
	

	protected boolean processObjekt(String uuid) {
		boolean beenProcessed = traversed.get().containsKey(uuid);
		
		if (!beenProcessed) traversed.get().put(uuid, null);
		
		return beenProcessed;
	}
        
	public static XMLGregorianCalendar dateTimeToXMLGregorianCalendar(DateTime dateTime) throws DatatypeConfigurationException {
		DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
		return dataTypeFactory.newXMLGregorianCalendar(dateTime.toGregorianCalendar());
	}
	
	public static XMLGregorianCalendar dateToXML(DateTime birthDate) throws DatatypeConfigurationException {
        XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
        xmlGregorianCalendar.setDay(birthDate.getDayOfMonth());
        xmlGregorianCalendar.setMonth(birthDate.getMonthOfYear());
        xmlGregorianCalendar.setYear(birthDate.getYear());
        return xmlGregorianCalendar;
	}
	
	public static DateTime XMLToDateTime(XMLGregorianCalendar xml) throws DatatypeConfigurationException {
        return new DateTime(xml.getYear(), xml.getMonth(), xml.getDay(), 0, 0,0, 0);
	}
	
	public static DateTime XMLToDate(XMLGregorianCalendar xml) throws DatatypeConfigurationException {
        return new DateTime(xml.getYear(), xml.getMonth(), xml.getDay(), xml.getHour(), xml.getMinute(),xml.getSecond(),xml.getMillisecond());
	}
}
